package com.cc.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.cc.models.BaseModel;
import com.cc.models.Power;

public class BeanUtil {
	
	public static <T> T request2Bean(HttpServletRequest request,Class<T> clazz){
    	try {
    		Field[] fields = clazz.getDeclaredFields();
			T t = clazz.newInstance();
			for (Field field : fields) {
	    		String value = request.getParameter(field.getName());
	    		if(!StringUtils.isEmpty(value)){
	    			field.setAccessible(true);
	    			if(field.getType().getName().equals("int"))
	    				field.set(t, Integer.valueOf(value));
	    			else
	    				field.set(t, value);
	    		}
			}
			return t;
		} catch (Exception e) {
			e.printStackTrace();
		} 
    	return null;
    }
	
	
	public static Map<String, Object> bean2Map(BaseModel bean){
		try{
			Map<String, Object> ret = new HashMap<String, Object>();
			Field[] fields = bean.getClass().getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true);
				ret.put(field.getName(), field.get(bean));
			}
			return ret;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	public static Map<String, Object> request2Map(HttpServletRequest request,Class<? extends BaseModel> clazz){
		BaseModel model = request2Bean(request, clazz);
		Map<String, Object> ret = bean2Map(model);
		return ret;
	}
	
	public static List<Power> list2Tree(List<Power> ls, Integer root, String childName){
		Map<Integer, Object> temp = new HashMap<Integer,Object>();
		for (Power power : ls) {
			Object object = temp.get(power.getPowerPId());
			if(object == null){
				List<Power> tp = new ArrayList<Power>();
				tp.add(power);
				temp.put(power.getPowerPId(), tp);
			}else{
				((List<Power>)object).add(power);
			}
		}
		List<Power> lists = setChild(root,temp);
		
		return lists;
	}
	private static List<Power>  setChild(Integer root,Map<Integer, Object> temp ){
		List<Power> lists = (List<Power>)temp.get(root);
		if(lists == null)
			return null;
		for (Power power : lists) {
			List<Power> object = (List<Power>)temp.get(power.getPowerId());
			if(object == null){
				continue;
			}
			else{
				power.setChildren(object);
				for (Power power2 : object) {
					power2.setChildren(setChild(power2.getPowerId(), temp));
				}
			}
		}
		return lists;
	}
	
}
